home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / c_toolbx.arc / EXPBACK.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-03-30  |  2.1 KB  |  94 lines

  1. /* expback.c - try reading a file backward  */
  2. #include "stdio.h"
  3. #include "cminor.h"
  4.  
  5. long ftell() ;
  6. FILE *gfopen() ;
  7. FILE * fp ;     /* file pointer
  8.  
  9. /* modes for seek */
  10. #define BOF_SEEK 0
  11. #define REL_SEEK 1
  12. #define EOF_SEEK 2
  13.  
  14. /* special return value for begining of file */
  15. #define BOF  (-2)
  16.  
  17. main()
  18. {
  19.   int    n  ;            /* put fread return value here */
  20.  
  21.   /* open the file */
  22.   fp = gfopen("test.dat","r",BIN_MODE)  ;
  23.   printf("\n gfopen returns - %d \n",fp) ;
  24.  
  25.   printf("\n position     char    char     position") ;
  26.   printf("\n  before      read    value     after\n") ;
  27.  
  28.   printf("\n                                       ") ;
  29.   printf("   start at end of file and read backward") ;
  30.   fseek(fp,0L,EOF_SEEK);
  31.  
  32.   /* read the file one character at a time  */
  33.   /* stop when we get to the beginning of the file  */
  34.  
  35.   while( get_and_print() != BOF )
  36.   { ; }
  37.  
  38.   printf("\n");
  39.   printf("\n                                       ") ;
  40.   printf("   move to position %2 and read",5) ;
  41.   fseek(fp,5L,BOF_SEEK) ;
  42.   get_and_print() ;
  43.  
  44.  
  45.   printf("\n") ;
  46.   printf("\n                                       ") ;
  47.   printf("   move to position %2",5)  ;
  48.   fseek(fp,5L,BOF_SEEK) ;
  49.   printf("\n                                       ") ;
  50.   printf("   then move backward 1 char and read") ;
  51.   fseek(fp,-1L,REL_SEEK) ;
  52.   get_and_print() ;
  53.  
  54.   fclose(fp) ;
  55. }
  56.  
  57. int get_and_print()
  58. {
  59.   int    c  ;
  60.  
  61.   printf("\n    %21d ",ftell(fp)) ;
  62.   c  =    get_previous_char() ;
  63.   printf("      ") ;
  64.   if( isgraphic(c) )
  65.   printf("    %c",c) ;
  66.   else if( c == '\n')
  67.      printf("   LF") ;
  68.   else if( c == '\r')
  69.      printf("   CR") ;
  70.   else if( c == EOF )
  71.      printf("  EOF") ;
  72.   else if( c == BOF )
  73.      printf("  BOF") ;
  74.   else if( c == 26 )
  75.      printf("Ctl-Z") ;
  76.   else printf("     ") ;
  77.   printf("    %3d",c)  ;
  78.   printf("         %21d ",ftell(fp)) ;
  79.   return(c) ;
  80. }
  81.  
  82. int get_previous_char()
  83. {
  84.   int c ;
  85.  
  86.   if( ftell(fp)  > 0 )
  87.     { fseek(fp,-1L,REL_SEEK) ;
  88.       c = getc(fp) ;
  89.       fseek(fp,-1L,REL_SEEK) ;
  90.       return( c ) ;
  91.     }
  92.   else return( BOF ) ;
  93. }
  94.